<template>
	<view class="container">
		<!-- 头像区域 -->
		<view class="user-section">
			<image class="bg" src="/static/user-bg.png"></image>
			<view class="portrait-box">
				<image class="portrait" :src="avatarUrl || userInfo.icon || '/static/missing-face.png'"></image>
			</view>
		</view>

		<!-- 表单区域 -->
		<view class="form-section">
			<!-- 头像设置 -->
			<view class="form-item">
				<text class="label">头像</text>
				<view class="value-box">
					<image class="avatar-preview" :src="avatarUrl || userInfo.icon || '/static/missing-face.png'"></image>
					<button class="get-btn" @click="getWxAvatar">获取微信头像</button>
				</view>
			</view>

			<!-- 昵称设置 -->
			<view class="form-item">
				<text class="label">昵称</text>
				<view class="value-box">
					<text class="nickname-text">{{ nickName || userInfo.nickname || '未设置' }}</text>
					<button class="get-btn" @click="getWxNickname">获取微信昵称</button>
				</view>
			</view>
		</view>

		<!-- 保存按钮 -->
		<view class="footer">
			<button class="save-btn" @click="saveUserInfo" :disabled="saving">
				{{ saving ? '保存中...' : '保存修改' }}
			</button>
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex';
	import {
		updateUserInfo
	} from '@/api/member.js';

	export default {
		data() {
			return {
				avatarUrl: '', // 新获取的头像
				nickName: '', // 新获取的昵称
				saving: false
			};
		},
		computed: {
			...mapState(['userInfo']),
		},
		onLoad() {
			// 初始化数据
			this.avatarUrl = this.userInfo.icon || '';
			this.nickName = this.userInfo.nickname || '';
		},
		methods: {
			...mapMutations(['login']),

			/**
			 * 获取微信头像
			 * 使用 wx.chooseAvatar （基础库 2.21.2+）
			 */
			getWxAvatar() {
				// 注意：chooseAvatar 需要在 button 组件的 open-type="chooseAvatar" 触发
				// 但为了更好的用户体验，我们使用 getUserProfile 同时获取
				this.getWxUserProfile('avatar');
			},

			/**
			 * 获取微信昵称
			 */
			getWxNickname() {
				this.getWxUserProfile('nickname');
			},

			/**
			 * 获取微信用户信息
			 * @param {String} type - 'avatar' | 'nickname' | 'both'
			 */
			getWxUserProfile(type) {
				uni.showLoading({
					title: '获取中...'
				});

				uni.getUserProfile({
					desc: type === 'avatar' ? '获取你的头像' : '获取你的昵称',
					success: (res) => {
						uni.hideLoading();

						const userInfo = res.userInfo;

						if (type === 'avatar' || type === 'both') {
							this.avatarUrl = userInfo.avatarUrl;
							console.log('获取到微信头像:', this.avatarUrl);
						}

						if (type === 'nickname' || type === 'both') {
							this.nickName = userInfo.nickName;
							console.log('获取到微信昵称:', this.nickName);
						}

						uni.showToast({
							title: '获取成功',
							icon: 'success'
						});
					},
					fail: (err) => {
						uni.hideLoading();
						console.error('获取微信信息失败:', err);
						uni.showToast({
							title: '用户取消授权',
							icon: 'none'
						});
					}
				});
			},

			/**
			 * 保存用户信息
			 */
			async saveUserInfo() {
				// 检查是否有修改
				if (this.avatarUrl === this.userInfo.icon && this.nickName === this.userInfo.nickname) {
					uni.showToast({
						title: '没有修改内容',
						icon: 'none'
					});
					return;
				}

				// 检查是否有内容
				if (!this.avatarUrl && !this.nickName) {
					uni.showToast({
						title: '请先获取头像或昵称',
						icon: 'none'
					});
					return;
				}

				this.saving = true;

				try {
					const response = await updateUserInfo({
						nickname: this.nickName,
						icon: this.avatarUrl
					});

					if (response.code === 200) {
						// 更新本地用户信息
						const updatedUserInfo = {
							...this.userInfo,
							nickname: this.nickName,
							icon: this.avatarUrl
						};

						this.login(updatedUserInfo);

						uni.showToast({
							title: '保存成功',
							icon: 'success'
						});

						// 延迟返回
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					} else {
						uni.showToast({
							title: response.message || '保存失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('保存用户信息失败:', error);
					uni.showToast({
						title: '保存失败，请重试',
						icon: 'none'
					});
				} finally {
					this.saving = false;
				}
			}
		}
	}
</script>

<style lang="scss">
	page {
		background: $page-color-base;
	}

	.container {
		padding-bottom: 120upx;
	}

	.user-section {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 360upx;
		padding: 40upx 30upx 0;
		position: relative;
		margin-bottom: 20upx;

		.bg {
			position: absolute;
			left: 0;
			top: 0;
			width: 100%;
			height: 100%;
			filter: blur(1px);
			opacity: .7;
		}

		.portrait-box {
			width: 180upx;
			height: 180upx;
			border: 6upx solid #fff;
			border-radius: 50%;
			position: relative;
			z-index: 2;
			box-shadow: 0 4upx 20upx rgba(0, 0, 0, 0.1);
		}

		.portrait {
			position: relative;
			width: 100%;
			height: 100%;
			border-radius: 50%;
		}
	}

	.form-section {
		background: #fff;
		border-radius: 16upx;
		margin: 0 30upx;
		padding: 0 30upx;
	}

	.form-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 30upx 0;
		border-bottom: 1px solid #f5f5f5;

		&:last-child {
			border-bottom: none;
		}

		.label {
			font-size: 30upx;
			color: $font-color-dark;
			font-weight: 500;
			min-width: 120upx;
		}

		.value-box {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: flex-end;
			gap: 20upx;
		}

		.avatar-preview {
			width: 80upx;
			height: 80upx;
			border-radius: 50%;
			border: 2upx solid #f0f0f0;
		}

		.nickname-text {
			font-size: 28upx;
			color: $font-color-dark;
			max-width: 300upx;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
		}

		.get-btn {
			padding: 0 24upx;
			height: 60upx;
			line-height: 60upx;
			font-size: 26upx;
			color: $base-color;
			background: #fff;
			border: 1px solid $base-color;
			border-radius: 30upx;

			&:after {
				border: none;
			}
		}

		.value {
			flex: 1;
			text-align: right;
			font-size: 28upx;
			color: $font-color-dark;

			&.readonly {
				color: $font-color-light;
			}
		}
	}

	.footer {
		position: fixed;
		left: 0;
		bottom: 0;
		width: 100%;
		padding: 20upx 30upx;
		background: #fff;
		box-shadow: 0 -2upx 10upx rgba(0, 0, 0, 0.05);
		z-index: 100;

		.save-btn {
			width: 100%;
			height: 88upx;
			line-height: 88upx;
			background: $base-color;
			color: #fff;
			font-size: 32upx;
			border-radius: 44upx;

			&:after {
				border: none;
			}

			&[disabled] {
				opacity: 0.6;
			}
		}
	}
</style>
